<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="关联记录配置" @ok="handleSubmit">
    <a-spin :spinning="spinningLoading">
      <BasicForm @register="registerForm" />
    </a-spin>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { omit } from 'lodash-es';
  import { defHttp } from '/@/utils/http/axios';

  export default defineComponent({
    name: 'LinkTableConfigModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const spinningLoading = ref(false);
      const fieldName = ref('');
      let oldValue = {};
      const [registerModal, { closeModal }] = useModalInner(async (data) => {
        console.log('data', data);
        oldValue = Object.assign({}, data.record);
        await setFieldsValue({ dictTable: data.record.dictTable });
        setTimeout(async () => {
          let otherValue = omit(data.record, 'dictTable');
          await setFieldsValue(otherValue);
          await clearValidate();
        }, 200);
        fieldName.value = data.fieldName;
      });
      const titleFieldName = ref('');
      const imageFieldName = ref('');
      const fieldOptions = ref([]);
      const imageFieldOptions = ref([]);
      async function getFieldOptions(tableName) {
        if (tableName) {
          const url = '/online/cgform/field/listByHeadCode';
          const dataList = await defHttp.get({ url, params: { headCode: tableName } });
          if (dataList && dataList.length > 0) {
            let arr1 = dataList.filter((item) => item.dbFieldName != 'id' && item.dbIsPersist == 1);
            console.log('字段字典', arr1);
            if (arr1.length > 0) {
              fieldOptions.value = arr1.map((item) => {
                return {
                  text: item.dbFieldTxt,
                  value: item.dbFieldName,
                };
              });
            } else {
              fieldOptions.value = [];
            }
            let arr2 = dataList.filter((item) => item.dbFieldName != 'id' && item.fieldShowType == 'image' && item.dbIsPersist == 1);
            console.log('图片字段', arr2);
            if (arr2.length > 0) {
              imageFieldOptions.value = arr2.map((item) => {
                return {
                  text: item.dbFieldTxt,
                  value: item.dbFieldName,
                };
              });
            } else {
              imageFieldOptions.value = [{ text: '无图片字段可以选择', value: '', key: '', disabled: true }];
            }
          } else {
            fieldOptions.value = [];
            imageFieldOptions.value = [{ text: '无图片字段可以选择', value: '', key: '', disabled: true }];
          }
        }
      }
      async function handleTableChange(tableName) {
        titleFieldName.value = '';
        imageFieldName.value = '';
        await getFieldOptions(tableName);
      }
      const otherFieldOptions = computed(() => {
        let arr = fieldOptions.value;
        let titleField = titleFieldName.value;
        let imageField = imageFieldName.value;
        return arr.filter((item) => item.value != titleField && item.value != imageField);
      });
      const formSchemas = [
        {
          label: 'rowKey',
          field: 'rowKey',
          component: 'Input',
          show: false,
        },
        {
          label: 'dictField',
          field: 'dictField',
          component: 'Input',
          defaultValue: 'id',
          show: false,
        },
        {
          label: '字段描述',
          field: 'dbFieldTxt',
          component: 'Input',
          required: true,
        },
        {
          label: '关联表',
          field: 'dictTable',
          component: 'JSearchSelect',
          required: true,
          componentProps: ({ formActionType }) => {
            return {
              dict: 'onl_cgform_head where copy_type = 0,table_txt,table_name',
              pageSize: 10,
              async: true,
              immediateChange: true,
              popContainer: '.link-table-config-modal',
              params: { order: 'desc', column: 'create_time' },
              onChange: async (name) => {
                if (oldValue.titleField || oldValue.otherFields) {
                  await formActionType.setFieldsValue({
                    titleField: '',
                    otherFields: '',
                    imageField: '',
                  });
                  await formActionType.clearValidate();
                }
                await handleTableChange(name);
              },
            };
          },
        },
        {
          label: '标题字段',
          field: 'titleField',
          component: 'JSearchSelect',
          required: true,
          componentProps: {
            async: false,
            popContainer: '.link-table-config-modal',
            dictOptions: fieldOptions,
            immediateChange: true,
            onChange: (str) => {
              titleFieldName.value = str;
              oldValue['titleField'] = str;
            },
          },
        },
        {
          label: '封面图片',
          field: 'imageField',
          component: 'JSearchSelect',
          componentProps: {
            async: false,
            popContainer: '.link-table-config-modal',
            dictOptions: imageFieldOptions,
            immediateChange: true,
            onChange: (str) => {
              imageFieldName.value = str;
              oldValue['imageFieldName'] = str;
            },
          },
        },
        {
          label: '其他字段',
          field: 'otherFields',
          component: 'JSelectMultiple',
          componentProps: {
            popContainer: '.link-table-config-modal',
            options: otherFieldOptions,
            onChange: (str) => {
              oldValue['otherFields'] = str;
              console.error('oldValue', oldValue);
            },
          },
        },
        {
          label: '显示方式',
          field: 'showType',
          component: 'Select',
          defaultValue: 'card',
          componentProps: {
            options: [
              { label: '卡片', value: 'card' },
              { label: '下拉框', value: 'select' },
            ],
          },
        },
        {
          label: '是否多选',
          field: 'multiSelect',
          component: 'RadioGroup',
          defaultValue: false,
          componentProps: {
            options: [
              { label: '否', value: false },
              { label: '是', value: true },
            ],
          },
        },
      ];
      const [registerForm, { validate, setFieldsValue, clearValidate, resetFields }] = useForm({
        schemas: formSchemas,
        showActionButtonGroup: false,
        labelAlign: 'right',
      });
      async function handleSubmit() {
        let data = await validate();
        data['fieldName'] = fieldName.value;
        emit('success', data);
        closeModal();
      }
      return {
        registerModal,
        spinningLoading,
        registerForm,
        handleSubmit,
      };
    },
  });
</script>
<style scoped></style>
